/**
 * 登录模块
 */
import wx from "utils/wx";
import { BUSINESS_BASE_API, WX_APP_ID, APP_ID } from "config";
import wxSocket from "utils/wx-socket";

export default {
  state: {
    deviceList: [],
    currentDevice: null,
    currentAttrs: null
  },
  mutations: {
    [ VUEX.DEVICE.SET_DEVICE_LIST ](state, payload) {
      state.deviceList = payload;
      if (!state.currentDevice && state.deviceList.length) {
        const currentDevice = wx.getStorageSync('CURRENT_DEVICE');
        const flag = state.deviceList.some(device => {
          if(currentDevice && currentDevice.did === device.did){
            Store.commit(VUEX.DEVICE.SET_CURRENT_DEVICE, device);
            return true;
          }
        })
        if(!flag){
          state.deviceList.some(device => {
            device.is_online && Store.commit(VUEX.DEVICE.SET_CURRENT_DEVICE, device);
            return device.is_online;
          })
        }
      }
    },
    [ VUEX.DEVICE.SET_CURRENT_DEVICE ](state, payload) {
      wx.setStorageSync('CURRENT_DEVICE', payload)
      state.currentDevice = payload;
      state.currentAttrs = null;
    },
    [ VUEX.DEVICE.SET_CURRENT_ATTRS ](state, payload) {
      state.currentAttrs = Object.assign(state.currentAttrs || {}, payload);
    }
  },
  actions: {
    getCurrentAttrs() {
      return new Promise(async resolve => {
        if(!Store.state.device.deviceList.length){
          await Store.dispatch('getDeviceList');
        }
        if (!Store.state.device.currentAttrs) {
          const device = Store.state.device.currentDevice;
          wxSocket.init({
            app_id: APP_ID,
            did: device.did,
            user_token: Store.state.login.token,
            onMessage: message => {
              switch (message.cmd) {
              case "subscribe_res":
                wxSocket.sendMessage("c2s_read", { did: device.did });
                break;
              case "s2c_noti":
                if (message.data.did === device.did) {
                  Store.commit(VUEX.DEVICE.SET_CURRENT_ATTRS, message.data.attrs);
                  resolve(message.data.attrs);
                }
                break;
              }
            }
          });
        } else {
          resolve(Store.state.device.currentAttrs);
        }
      });
    },
    async updateDeviceAttrs(ctx, attrs) {
      wxSocket.sendMessage('c2s_write', {
        did: Store.state.device.currentDevice.did,
        attrs: attrs,
      })
      Store.commit(VUEX.DEVICE.SET_CURRENT_ATTRS, attrs);
    },
    async getDeviceList() {
      const result = await wx.request({
        url: "/app/bindings",
        data: {
          show_disabled: 0,
          limit: 40,
          skip: 0
        }
      });
      const list = result.devices || [];
      Store.commit(VUEX.DEVICE.SET_DEVICE_LIST, list);
      return list;
    }
  }
};
